<?php

namespace app\api\controller\v1;
use app\api\validate\AddressNew;
use app\api\service\Token as TokenService;
use app\api\model\User as UserModel;
use app\lib\exception\UserException;
use app\lib\exception\SuccessMessage;
use app\api\controller\BaseController;

class Address extends BaseController
{
    // 只有createOrUpdateAddress的方法需要checkPrimaryScope的前置操作
    # checkPrimaryScope 必须用小写（巨坑）
    protected $beforeActionList = [
        'checkPrimaryScope' => ['only' => 'createorupdateaddress']
    ];

    public function createOrUpdateAddress()
    {
        $validate = new AddressNew();
        $validate->goCheck();
        // 通过token来查询id
        $uid = TokenService::getCurrentUid(); 
        $user = UserModel::get($uid);
        if(!$user){
          throw new UserException();  
        }

        $dataArray = $validate->getDataByRule(input('post.'));

        $userAddress = $user->address;
        if(!$userAddress){
            $user->address()->save($dataArray);
        }else{
            $user->address->save($dataArray);
        }
        return json(new SuccessMessage(),201);
    }

}